import os
import posixpath
import amara
import psycopg2
from Ft.Lib import Uri

from brightcontent.core.store import COMMON_PREFIXES, ATOM10_NS
from brightcontent.util import fixup_namespaces, quick_xml_scan


def do_import(source, dsn, envelope_file):
    doc = amara.parse(source, prefixes=COMMON_PREFIXES)

    try:
        conn = psycopg2.connect(dsn)
    except psycopg2.OperationalError:
        import sys; print >> sys.stderr, "Set up the database.  Something along the lines of:\n\t'psql -f etc/postgres8.sql template1'"
        raise
    curs = conn.cursor()

    queryset = []
    for count, entry in enumerate(doc.feed.entry):
        print unicode(entry.id)
        self_link = entry.xml_xpath(u'string(atom:link[@rel="self"]/@href)')
        nick = 'entry' + str(count)
        if self_link:
            try:
                nick = posixpath.split(Uri.SplitUriRef(self_link)[2])[1]
            except (KeyboardInterrupt, SystemExit):
                raise
            except:
                pass
        params = {
            'atomid': unicode(entry.id).encode('utf-8'),
            'updated': str(entry.updated),
            'nick': nick,
            'body': entry.xml(),
            }
        queryset.append(params)
    curs.executemany('INSERT INTO entry (atomid, updated, nickname, body) VALUES (%(atomid)s, DATE %(updated)s, %(nick)s, %(body)s)', queryset)
    conn.commit()

    #Set up Weblog Atom envelope
    envelope = amara.create_document(u"atom:feed", ns=ATOM10_NS)
    for nonentry in doc.feed.xml_xpath(u'*[not(self::atom:entry)]'):
        envelope.feed.xml_append(nonentry)
    f = open(envelope_file, 'w')
    fixup_namespaces(envelope)
    f.write(envelope.xml(indent=u"yes"))
    f.close()
    return


if __name__ == '__main__':
    #e.g. usage:
    #python etc/import-feed-into-postgres.py http://copia.ogbuji.net/blog/index.atom dbname=brightcontent
    import sys
    input_file_or_url = sys.argv[1]
    try:
        db_connection = sys.argv[2]
    except IndexError:
        db_connection = 'dbname=brightcontent'
    try:
        envelope_file = sys.argv[3]
    except IndexError:
        envelope_file = '/etc/bc/envelope.xml'
    do_import(input_file_or_url, db_connection, envelope_file)

